package com.yxr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxr.constants.SystemCanstants;
import com.yxr.domain.entity.Menu;
import com.yxr.mapper.MenuMapper;
import com.yxr.service.MenuService;
import com.yxr.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2024-07-11 17:51:10
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {



    @Override
    public List<String> selectPeremsByUserId(Long id) {
         //如果是超级管理员返回所有权限
        if (id==1L){
            LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            menuLambdaQueryWrapper.in(Menu::getMenuType, SystemCanstants.PERMISSION_MENUE,SystemCanstants.PERMISSION_BUTTON);
            menuLambdaQueryWrapper.eq(Menu::getStatus,SystemCanstants.ARTICLE_STATUS_NORMAL);
            List<Menu> list = list(menuLambdaQueryWrapper);
            List<String> collect = list.stream().map(Menu::getPerms).collect(Collectors.toList());
            return collect;
        }
          //查询用户的权限信息

        return getBaseMapper().selectPeremsByUserId(id);
    }

    @Override
    public List<Menu> selectRouterMenuTreeByUserId(Long userId) {
        MenuMapper menuMapper = getBaseMapper();
        List<Menu> menus =null;
        //判断是否是管理员
        if(SecurityUtils.isAdmin()){
            //是，返回所有符合要求的menu
            menus = menuMapper.selectAllRouterMenu();
        }else {
            //不是，当前用户所具有的menu
            menus =menuMapper.selectRouterMenuTreeByUserId(userId);
        }
        //构建tree父子关系
        List<Menu> menuTree = builderMenuTree(menus,0L);
        return menuTree ;
    }

    private List<Menu> builderMenuTree(List<Menu> menus,Long parentId) {
      List<Menu> menuTree =  menus.stream()
                .filter(menu ->menu.getParentId().equals(parentId))
                .map(menu->menu.setChildren(getChildren(menu,menus)))
                .collect(Collectors.toList());
      return menuTree;
    }


    //获取传入参数的子菜单
    private List<Menu> getChildren(Menu menu,List<Menu> menus){
       List<Menu> childrenList = menus.stream().filter(m->m.getParentId().equals(menu.getId()))
                .collect(Collectors.toList());
       return childrenList;

    }


}
